// pages/open/open.js
const config = require('../../config.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    locationData: {},
    gymData:[],
    maskShow: false,
    gymID: '',
    playData: {},
    messErr: '',
    resultData: '',
    messSucc: false,
    errCode: false,
    succCode: false,
    closeData: {},
    onlyTf: false,
    // 临时
    tempData: '',
    paySucc: false,
    payCode: false,
  },

  // 手机弹出微信授权设置
  handler: function (e) {
    console.log(e)
    if (e.detail.authSetting["scope.userLocation"]) {
      this.setData({
        maskShow: false,
      })
      wx.showLoading({
        title: '加载中',
      })
      this.getLocation();
    }
  },
  // 获取最近的健身房
  getNearGym: function() {
    let that = this;
    wx.request({
      url: config.nearGym,
      method: 'GET',
      data: {
        lat: this.data.locationData.latitude,
        lng: this.data.locationData.longitude,
      },
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token_type') + ' ' + wx.getStorageSync('access_token'),
      },
      success: function (res) {
        // console.log(res.data.data.id, "nearGym")
        wx.hideLoading();
        that.setData({
          gymData: res.data.data,
          gymID: res.data.data[0].id,
          maskShow: false,
        })
        that.refreshPlay();
      }
    })
  },
  // 剩余席位
  refreshPlay: function () {
    var that = this;
    // console.log(this.data.gymID)
    wx.request({
      url: config.playRe + "/" + this.data.gymID,
      method: 'GET',
      data: {
      },
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token_type') + ' ' + wx.getStorageSync('access_token'),
      },
      success: function (res) {
        wx.hideLoading();
        that.setData({
          playData: res.data.data
        })
        // console.log(res, "result")
      }
    })
  },
  // 扫码
  scanCode: function () {
    var that = this;
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        console.log(res,"res")
        this.setData({
          resultData: res.result
        });
        let apiURL = '';
        var regIn = RegExp(/in/);
        var regOut = RegExp(/out/);
        if(res.result.match(regIn)){
          apiURL = "https://jd.trc-demo.com/api/v1/app/gym/openIn?"
        } else if (res.result.match(regOut)){
          apiURL = "https://jd.trc-demo.com/api/v1/app/gym/settlement?"
        }
        // console.log(apiURL)
        wx.request({
          url: apiURL + res.result,
          method: 'GET',
          data: {
          },
          header: {
            'content-type': 'application/json',
            'Authorization': wx.getStorageSync('token_type') + ' ' + wx.getStorageSync('access_token'),
          },
          success: function (res) {
            // code为200的时候，正常流程，出门扫码支付
            // code为300的时候，正常流程，进门扫码
            // code为302的时候，异常流程，进门扫码两次，通过temp判断是否为临时出门
            if (res.data.resultCode == 200){
              that.setData({
                closeData: res.data.data,
                succCode: true,
              })
              if (res.data.data.vip == true && res.data.data.enough == false) {
                that.setData({
                  onlyTf: true,
                })
              }
              setTimeout(() => {
                that.setData({
                  succCode: false,
                })
              }, 10000);
            }else if (res.data.resultCode == 300){
              that.setData({
                messSucc: true,
                errCode: true,
                messErr: res.data.resultMessage,
              })
              that.setData({
                tempData: null
              });
            } else if(res.data.resultCode == 302){
              console.log(res,"302")
              if (res.data.data.record.temp == null){
                that.setData({
                  tempData: res.data.data.record.temp
                });
                that.setData({
                  messSucc: false,
                  errCode: true,
                  messErr: res.data.resultMessage,
                })
              } else{
                that.setData({
                  tempData: res.data.data.record.temp
                });
                wx.request({
                  url: "https://jd.trc-demo.com/api/v1/app/gym/settlement?" + that.data.resultData,
                  method: 'GET',
                  data: {
                  },
                  header: {
                    'content-type': 'application/json',
                    'Authorization': wx.getStorageSync('token_type') + ' ' + wx.getStorageSync('access_token'),
                  },
                  success: function (res) {
                    that.setData({
                      closeData: res.data.data,
                      succCode: true,
                    })
                    if (res.data.data.vip == true && res.data.data.enough == false){
                      that.setData({
                        onlyTf: true,
                      })
                    }
                    setTimeout(() => {
                      that.setData({
                        succCode: false,
                      })
                    },10000);
                  }
                })
              }
            } else if (res.data.resultCode == 400) {
              that.setData({
                messSucc: false,
                errCode: true,
                messErr: res.data.resultMessage,
              })
            }
            that.refreshPlay();                     
          }
        })
      }
    })
  },
  // 钱包支付
  payWall: function () {
    var that = this;
    console.log(that.data.tempData,"tempData")
    if (that.data.tempData == "temp") {
      wx.request({
        url: config.payMon,
        method: 'GET',
        data: {
          gym_id: this.data.closeData.gym_id,
          end_time: this.data.closeData.end_time,
        },
        header: {
          'content-type': 'application/json',
          'Authorization': wx.getStorageSync('token_type') + ' ' + wx.getStorageSync('access_token'),
        },
        success: function (res) {
          // console.log(res, "payWall")
          that.setData({
            paySucc: true,
            payCode: true,
            messErr: res.data.resultMessage,
          })
          that.refreshPlay();
        }
      })
    } else {
      wx.request({
        url: config.payWall,
        method: 'GET',
        data: {
          gym_id: this.data.closeData.gym_id,
          end_time: this.data.closeData.end_time,
        },
        header: {
          'content-type': 'application/json',
          'Authorization': wx.getStorageSync('token_type') + ' ' + wx.getStorageSync('access_token'),
        },
        success: function (res) {
          console.log(res, "payWall")
          that.setData({
            succCode: false,
            messSucc: true,
            errCode: true,
            messErr: res.data.resultMessage,
          })
          that.refreshPlay();
        }
      })
    }
  },
  // 关闭扫码弹窗
  celErr: function () {
    this.setData({
      errCode: false,
    })    
  },
  payErr: function () {
    this.setData({
      payCode: false,
    })
  },
  clpclose: function () {
    this.setData({
      succCode: false,
    })
  },
  // 去续卡
  connCard: function () {
    wx.navigateTo({
      url: '/pages/card/card',
    })
  },
  // 余额不足去充值（去充值）
  connWall: function () {
    wx.navigateTo({
      url: '/pages/wallet/wallet',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
    this.getLocation();
  },
  getLocation: function(){
    let that = this;
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              // 用户已经同意小程序使用地理位置功能
              wx.getLocation({
                type: 'wgs84',
                success: function (res) {
                  // console.log(res, "res")
                  that.setData({
                    locationData: res
                  })
                  var latitude = res.latitude
                  var longitude = res.longitude
                  var speed = res.speed
                  var accuracy = res.accuracy
                  that.getNearGym();
                }
              })
            },
            fail() {
              console.log(1)
              that.setData({
                maskShow: true,
              })
            },
          })
        }else {
          // let that = this;              
          wx.getLocation({
            type: 'wgs84',
            success: function (res) {
              // console.log(res, "res2")
              that.setData({
                locationData: res
              })
              var latitude = res.latitude
              var longitude = res.longitude
              var speed = res.speed
              var accuracy = res.accuracy
              that.getNearGym();
            }
          })
          // console.log(res, "res2")
        }
      },
      
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getLocation();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})